/*
    http://bhepple.freeshell.org

    Copyright (C) 2010 Bob Hepple <bhepple@freeshell.org>

    This program is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program; see the file COPYING.  If not, write to
    the Free Software Foundation, Inc., 59 Temple Place - Suite 330,
    Boston, MA 02111-1307, USA.

*/

/**
 * \file very simple use of a dynamic array - all elements are the
 * same length and no callbacks are used.
 *
 * To run from the src directory:
 *
 * libtool --mode=execute valgrind ./tests/array1
 *
 * NB for the purposes of simplicity in illustration, we're ignoring
 * the possibility of OOM conditions here - checking of return values
 * should be done.
 */

#include <stdio.h>
#include <stdlib.h>
#include <tba.h>

void *xcalloc (size_t nmemb, size_t size) { return(calloc(nmemb, size)); }
void *xmalloc (size_t size) { return(malloc(size)); }
void *xrealloc(void *oldbuf, size_t size) { return(realloc(oldbuf, size)); }
void xfree(void *buf) { free(buf); }

#define TEXT_SIZE 50

typedef struct {
    int count;
    char description[TEXT_SIZE];
} my_payload;

void format_payload(my_payload *pl, const int i)
{
    pl->count = i;
    snprintf(pl->description, TEXT_SIZE, "this is payload %d", i);
}

void print_payload(const my_payload *pl)
{
    printf("%d: desc=%s\n", pl->count, pl->description);
}

int main(int argc, char **argv)
{
    int i;

    // alloc space for 500 my_payloads:
    tba a = tba_new(500, sizeof(my_payload), NULL, NULL, NULL, NULL); 
    // a[0..499] are alloc'd; a[500] == NULL
    for (i = 0; a[i]; i++) {
        format_payload((my_payload *)a[i], i);
    }

    print_payload((my_payload *)a[234]);
    print_payload((my_payload *)a[499]);

    // add a new element to the end:
    tba_insert(&a, -1, 1);
    format_payload((my_payload *)a[500], 500);
    print_payload((my_payload *)a[500]);

    tba_free(&a); // all gone
    return(0);
}

/* compile this with something like:

cc -Wall -I.. -o array1 array1.c ../.libs/libctoolbox.a

*/
